//
//  CreateJobScheculeDateOfInstallView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2/3/2023.
//

import UIKit
import SnapKit
import FSCalendar
import RxCocoa
import RxSwift
class CreateJobScheculeDateOfInstallView: CreateJobBaseView {
    fileprivate let gregorian = Calendar(identifier: .gregorian)
    var refreshJobsByDateClosure: ((Date)->Void)?
    private var notCompletedList: [String] = [String]()
    private var completedList: [String] = [String]()
    let calendar = DIYFSCalendar()
    @objc dynamic var installDate: Date = Date()
    let installDateLabel = ContentLabel(R.font.interRegular(size: 16))
    override func setUpContentView() {
        //title
        let scheduleDateTitle = TitleLabelWithRequired(R.string.localizable.scheduledDateOfInstall())
        self.contentView.addSubview(scheduleDateTitle)
        scheduleDateTitle.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //installDateLabel
        self.contentView.addSubview(installDateLabel)
        installDateLabel.snp.makeConstraints { make in
            make.top.equalTo(scheduleDateTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(scheduleDateTitle).offset(TitleLabelWithRequired.titleLefitMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //not completed
        let notCompletedCircleView = View(hexStr: "#A2A2A2FF")
        notCompletedCircleView.layer.cornerRadius = 4
        notCompletedCircleView.clipsToBounds = true
        self.contentView.addSubview(notCompletedCircleView)
        notCompletedCircleView.snp.makeConstraints { make in
            make.top.equalTo(installDateLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(scheduleDateTitle)
            make.height.width.equalTo(8)
        }
        //
        let notCompletedLabel = ContentLabel(R.font.dinMedium(size: 11),hexStr: "#292D3266")
        notCompletedLabel.text = R.string.localizable.notCompleted()
        self.contentView.addSubview(notCompletedLabel)
        notCompletedLabel.snp.makeConstraints { make in
            make.centerY.equalTo(notCompletedCircleView)
            make.left.equalTo(notCompletedCircleView.snp.right).offset(8)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //completed
        let completedCircleView = View(hexStr: "#005D2DFF")
        completedCircleView.layer.cornerRadius = 4
        completedCircleView.clipsToBounds = true
        self.contentView.addSubview(completedCircleView)
        completedCircleView.snp.makeConstraints { make in
            make.centerY.equalTo(notCompletedCircleView)
            make.left.equalTo(notCompletedLabel.snp.right).offset(20)
            make.height.width.equalTo(8)
        }
        //
        let completedLabel = ContentLabel(R.font.dinMedium(size: 11),hexStr: "#292D3266")
        completedLabel.text = R.string.localizable.completed()
        self.contentView.addSubview(completedLabel)
        completedLabel.snp.makeConstraints { make in
            make.centerY.equalTo(notCompletedCircleView)
            make.left.equalTo(completedCircleView.snp.right).offset(8)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //calendar
        self.contentView.addSubview(calendar)
        calendar.snp.makeConstraints { make in
            make.top.equalTo(notCompletedCircleView.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(notCompletedCircleView)
            make.right.equalTo(-Constant.AllOutMargin)
            make.bottom.equalToSuperview()
        }
        calendar.drawCorner(byRoundingCorners: [.topLeft,.topRight],backColorHexStr: "#9FACBE1A")
        calendar.dataSource = self
        calendar.delegate = self
        calendar.allowsMultipleSelection = false//不允许多选
        calendar.scope = .month//选择月模式
        calendar.appearance.borderRadius = 0//选中背景没有圆角，显示为正方形的背景
        calendar.placeholderType = .none//只显示这个月的日期
        calendar.firstWeekday = 1//周的第一天从sunday开始，2：表示从Monday开始
        //header
        calendar.headerHeight = 44//Header的高度
        calendar.appearance.headerTitleFont = R.font.interSemiBold(size: 16)//March 2023的字体
        calendar.appearance.headerTitleColor = UIColor(hexStr: "#292D32")//月份的显示颜色
        calendar.appearance.headerTitleAlignment = .left//March 2023左靠齐
        calendar.appearance.headerSeparatorColor = .clear//March 2023下边的分割线颜色
//        calendar.appearance.headerTitleOffset = CGPoint(x: 16, y: 0)//March 2023的偏移量
        //
        calendar.scrollDirection = .vertical//垂直滚动
        calendar.pagingEnabled = false//取消翻页,翻页设置为false，
        //calendar.pagingEnabled设置为true，下边两行代码有效；否则失效
//        calendar.appearance.headerMinimumDissolvedAlpha = 1//
//        calendar.calendarHeaderView.//drawCorner(byRoundingCorners: [.topLeft,.topRight],backColorHexStr: "#005D2D1A")//设置header（March 2023）的圆角和背景颜色
        
        //weekday
        calendar.weekdayHeight = 36//周几标题的高度
        calendar.rowHeight = 55//每个日期的单元格高度
        calendar.appearance.headerDateFormat = "   MMMM yyyy"
        calendar.appearance.caseOptions = .weekdayUsesUpperCase//星期(MON)三个字母大写
        calendar.appearance.weekdayFont = R.font.interRegular(size: 13)//周标题的字体
        calendar.appearance.weekdayTextColor = UIColor(hexStr: "#292D3266")//周标题字体颜色
        //day
        calendar.appearance.titleFont = R.font.interRegular(size: 16)//日期的字体
        calendar.appearance.titleDefaultColor = UIColor(hexStr: "#292D32")//日期的没选中的颜色
        //颜色
        calendar.appearance.selectionColor = .clear//UIColor(hexStr: "#9FACBE").withAlphaComponent(0.5)//UIColor(hexStr: "#9FACBE80")//选中背景的颜色
//        calendar.appearance.todayColor = UIColor(hexStr: "#292D32")//今天默认的背景颜色
//        calendar.appearance.todaySelectionColor = UIColor(hexStr: "#9FACBE").withAlphaComponent(0.5)//今天的选中的背景颜色//
        //注册自定义Cell
        calendar.register(DIYCalendarCellForScheduleDateOfInstall.self, forCellReuseIdentifier: DIYCalendarCellForScheduleDateOfInstall.reuseCellIdentifier)
        calendar.registerHeader(DIYFSCalendarStickerHeader.self, forHeaderReuseIdentifier: "header")
        //
        self.rx.observe(Date.self, "installDate").subscribe(onNext: {[weak self] date in
            guard let strongSelf = self else { return  }
            if let _ = date{
                strongSelf.installDateLabel.text = DateUtil().getDatetimeStr(date, format: "dd/MM/yyyy")
            }
        }).disposed(by: self.disposeBag)
    }
    func setData(notDoneList: [String], doneList: [String]){
        self.notCompletedList = notDoneList
        self.completedList = doneList
        self.calendar.reloadData()
        
    }
}
extension CreateJobScheculeDateOfInstallView: FSCalendarDataSource, FSCalendarDelegate , FSCalendarDelegateAppearance {
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        self.installDate = date
        self.configureVisibleCells()
    }
    //MARK: - 最小日期
    func minimumDate(for calendar: FSCalendar) -> Date {
        return DateUtil().getServeralYearOfToday(date: Date(), year: -1,day: 1)
    }
    
    //MARK: -
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCell(withIdentifier: DIYCalendarCellForScheduleDateOfInstall.reuseCellIdentifier, for: date, at: position)
        return cell
    }
    func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        self.configure(cell: cell, for: date, at: position)
    }
    // MARK: - Private functions
    private func configureVisibleCells() {
        calendar.visibleCells().forEach { (cell) in
            let date = calendar.date(for: cell)
            let position = calendar.monthPosition(for: cell)
            self.configure(cell: cell, for: date!, at: position)
        }
    }
    private func configure(cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        let diyCell = (cell as! DIYCalendarCellForScheduleDateOfInstall)
        //1. 今天的黑色圆角shaperlayer
        diyCell.todayBackLayer.isHidden = !self.gregorian.isDateInToday(date)
        //2.今天的日期颜色，和其他日期的颜色
        if self.gregorian.isDateInToday(date){//
            diyCell.titleLabel.textColor = .white
        }else{
            diyCell.titleLabel.textColor = UIColor(hexStr: "#292D32")
        }
        //3.选中时，自定义背景layer的显示
        let today = DateUtil().getDatetimeStr(self.installDate,format: "yyyy-MM-dd")
        let currentDate = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
        if today == currentDate {//选中时
            diyCell.selectBackLayer.isHidden = false
        }else{//选中时，非今天的颜色
            diyCell.selectBackLayer.isHidden = true
        }
        //4.是否显示event
        let dateStr = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
        let completedFlag = self.completedList.contains(dateStr)
        let notCompletedFlag = self.notCompletedList.contains(dateStr)
        
        if completedFlag || notCompletedFlag{
            diyCell.eventCircleLayer.isHidden = false
            if notCompletedFlag {
                diyCell.eventCircleLayer.fillColor = UIColor(hexStr: "#A2A2A2").cgColor
            }else{
                diyCell.eventCircleLayer.fillColor = UIColor(hexStr: Constant.ThemeColorHexStr).cgColor
            }
        }else{
            diyCell.eventCircleLayer.isHidden = true
        }
        
    }
//    //MARK: -选中时日期的颜色
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleSelectionColorFor date: Date) -> UIColor? {
//        let today = DateUtil().getDatetimeStr(Date(),format: "yyyy-MM-dd")
//        let currentDate = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
//        if today == currentDate {//选中时，今天的颜色
//            return .black
//        }else{//选中时，非今天的颜色
//            return .black
//        }
//    }
    
    //MARK: -有event的date，显示几个点
//    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
//        let dateStr = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
//        if self.completedList.contains(dateStr) || self.notCompletedList.contains(dateStr){
//            return 1
//        }
//        return 0
//    }
//    //MARK: - 选中时event的的颜色，分为not completed和completed两种
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventSelectionColorsFor date: Date) -> [UIColor]? {
//        return self.setEventColor(date)
//    }
//    //MARK: - event绿点的偏移量
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventOffsetFor date: Date) -> CGPoint {
//        return CGPoint(x: 0, y: 2)
//    }
//    //MARK: - event的默认的颜色，分为not completed和completed两种
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
//        return self.setEventColor(date)
//    }
    //MARK: - 翻页
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        self.refreshJobsByDateClosure?(calendar.currentPage)
    }
    //MARK: - 设置event的color
//    private func setEventColor(_ date: Date) -> [UIColor]? {
//        let dateStr = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
//        if self.completedList.contains(dateStr) {
//            return [UIColor(hexStr: Constant.ThemeColorHexStr)]
//        }
//        
//        if self.notCompletedList.contains(dateStr){
//            return [UIColor(hexStr: "#A2A2A2")]
//        }
//        return nil
//    }
}

